package com.alibaba.middleware.hsf.guide.serial.hessian.comparator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Comparator;
import java.util.TreeMap;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * <pre>
 * 验证Java不支持同名字段的序列化
 * 但是反序列化是，按照childValue和fatherValue分别给子类的filed字段进行连续赋值，最终以fatherValue为结果
 * </pre>
 * 
 * @author weipeng2k 2015年10月8日 下午4:56:43
 */
public class JavaSerial {
    
    static File file;
    
    @BeforeClass
    public static void createFile() {
        try {
            file = File.createTempFile("javaserial", "dat");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    @Test
    public void serial() throws Exception {
        TreeMap<String, String> map = new TreeMap<String, String>(new MapComparator());
        
        for (int i = 0; i < 10; i++) {
            map.put(String.valueOf(i), String.valueOf(i));
        }
        
        System.out.println(map);
        
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
        out.writeObject(map);
        out.flush();
        out.close();
    }
    
    @SuppressWarnings("unchecked")
    @Test
    public void deserial() throws Exception {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        TreeMap<String, String> cl = (TreeMap<String, String>) in.readObject();
        System.out.println(cl);
        in.close();
    }
    
    @AfterClass
    public static void removeFile() {
        file.delete();
    }
    
    static class MapComparator implements Comparator<String>, Serializable {
        
        /**
         * 
         */
        private static final long serialVersionUID = 6302410361330307615L;
        
        @Override
        public int compare(String o1, String o2) {
            return -o1.compareTo(o2);
        }
        
    }
}
